<?php
require_once('wpfunctions.php');
require_once('psalmfunctions.php');
require_once('lyfunctions.php');
require_once('liturgyfunctions.php');
$gregorioBinary = 'gregorioSVN';
if($_REQUEST['oldgreg']) {
  $gregorioBinary = 'gregorio';
}
$slightVerticalSpaceAllowPageBreak = '[0.0514in]';
$slightVerticalSpaceNoPageBreak = '*[0.0514in]';
$slightVerticalSpace = $slightVerticalSpaceNoPageBreak;

function removeOverridenSiglia($siglia,$overrideSiglia) {
  if($overrideSiglia) {
    $sigliaArray = explode(', ',$siglia);
    for ($i=count($sigliaArray)-1; $i >= 0; $i--) { 
      if(in_array($sigliaArray[$i],$overrideSiglia)) {
        array_splice($sigliaArray, $i, 1);
      }
    }
    $siglia = implode(', ',$sigliaArray);
  }
  return $siglia;
}

function prepareSiglia($siglia,$italicline) {
  if($siglia) {
    $siglia = preg_replace('/(?:,\s*)?[Ii]con-(white|half|black|asterisk)/', '\\hspace{1.5pt} \\raisebox{-0.375pt}{\\includegraphics[height=5.25pt]{library/\\string~icons/$1}}', $siglia);
    $siglia = preg_replace('/}}\\\\hspace{1.5pt}/','}}\\hspace{0.5pt}', $siglia);
    //$siglia = preg_replace('/(?:,\s*)?asterisk/', ' \raisebox{-4pt}{\\fontsize{{$template['size12']}}{{$template['size12']}}\\selectfont{*}}', $siglia);
    if($italicline && !preg_match('/^\s*$/',$italicline) && !preg_match('/^\s*\\\\hspace{1.5pt} \\\\raisebox{-0.375pt}{\\\\includegraphics/',$siglia)) {
      $italicline .= ' · ';
    }
    $italicline .= '\textsc{' . $siglia . '}';
  }
  return $italicline;
}

function texForRubricSubsection($rubric) {
  global $template;
  $topspace = '\vspace{23.4pt}%space above rubric section
';
  $rubrictitlesize = $rubric['titlesize']? $rubric['titlesize'] : $rubric['rubrictitlesize'];
  $rubrictitlealignment = $rubric['titlealignment']? $rubric['titlealignment'] : $rubric['rubrictitlealignment'];
  $rubrictextalignment = $rubric['textalignment']? $rubric['textalignment'] : $rubric['rubrictextalignment'];
  $rubricsize = $rubric['size']? $rubric['size'] : $rubric['rubricsize'];
  $rubricrubric = $rubric['rubric'];
  $title = $rubric['title'];
  if($rubrictitlesize == '') {
    $rubrictitlesize = '15';
  }
  $rubrictitlesize = $template["size$rubrictitlesize"];
  if($rubrictitlealignment == '') {
    $rubrictitlealignment = 'center';
  }
  if($rubrictextalignment == 'center') {
    $rubrictextalignment = '\\centering ';
  } else {
    $rubrictextalignment = '';
  }
  if($title && strlen($title) > 0 && $rubrictitlealignment == 'center') {
    $rubricAlignment = '\\centering ';
    $title = applyTexBoldItalics($title);
    $title = "$rubricAlignment$title
\\nopagebreak
\\\\";
  } else {
    $rubricAlignment = '\\raggedright';
  }
  if($title) {
    $title = <<<EOF
{\\noindent\\fontsize{{$rubrictitlesize}}{{$rubrictitlesize}}\\selectfont $title

}
EOF
;
    $vspace = '\\vspace{15pt}';
  } else {
    $title = '';
    $vspace = '';
  }
  if(!$rubricsize) {
    $rubricsize = 10;
  }
  $rubricsize = $template["size$rubricsize"];
  if($rubricrubric && strlen($rubricrubric) > 0) {
    $HACK = $rubricsize == 12? '[2.25pt]' : '';
    // This HACK is necessary because I couldn't figure out why the font leading wasn't getting set properly, so I need to add the extra space at the ends of lines.
    $rubricrubric = escapeTex(applyEmph(preg_replace('/(\r?\n)+/',"\\\\\\\\$HACK\n",$rubricrubric)));
    $rubricrubric = <<<EOF
$vspace
%\\setlength{\\parindent}{0in}
{{$rubrictextalignment}{\\fontsize{{$rubricsize}}{{$rubricsize}}\\selectfont\\textit{{$rubricrubric}}}

}
EOF
;
  } else {
    $rubricrubric = '';
  }
  $title = escapeTeX($title);
  return "$topspace %
$title
$rubricrubric%
";
}
$edition = $_REQUEST['edition'];
$save = $_REQUEST['save'];
$supertitle = mb_strtolower($_REQUEST['supertitle'],'UTF-8');
$fname = mb_strtolower($_REQUEST['filename'],'UTF-8');
$title = mb_strtolower($_REQUEST['title'],'UTF-8');
$subtitle = $_REQUEST['subtitle'];
$includeverses = $_REQUEST['includeverses'];
if($includeverses === '') {
  $includeverses = false;
} else {
  $includeverses = true;
  $_POST['includeverses'] = '1';
}
$globalOverrideTextLeft = $_REQUEST['globalOverrideTextLeft'];
$globalOverrideTextRight = $_REQUEST['globalOverrideTextRight'];
$globalOverrideHeader = $_REQUEST['globalOverrideHeader'];
$overrideSiglia = $_REQUEST['overrideSiglia'];
if($overrideSiglia) {
  $overrideSiglia = explode(', ', $overrideSiglia);
}
$template = $_REQUEST['template'];
$genres = $_REQUEST['genre'];
$genrenumbers = $_REQUEST['genrenumber'];
$genrequalifiers = $_REQUEST['genrequalifier'];
$engravings=$_REQUEST['engraving'];
$chantengravings=json_decode($_REQUEST['engravings'],true);
$verses=json_decode($_REQUEST['verses'],true);
$siglias = $_REQUEST['siglia'];
$addtoengravings=$_REQUEST['addtoengraving'];
$removetranslations = $_REQUEST['removetranslation'];
$raggedlasts = $_REQUEST['raggedlast'];
$numverseses = $_REQUEST['numverses'];
$psalmtones = $_REQUEST['psalmtone'];
$harmonizedpsalmtones = $_REQUEST['harmonizedpsalmtone'];
$sectionIDs = $_REQUEST['sectionID'];
$sectionTypes=$_REQUEST['sectiontype'];
$footer = $_REQUEST['footer'];
$footerText = $_REQUEST['footertext'];
$spaceBelowChants = $_REQUEST['spacebelowchant'];
$spaceAboveChants = $_REQUEST['spaceabovechant'];
$spaceBeforeFirstSystems = $_REQUEST['spacebeforefirstsystem'];
$spaceBetweenSystemss = $_REQUEST['spacebetweensystems'];
$lyricPaddings = $_REQUEST['lyricPadding'];
$spaceAfterLastSystems = $_REQUEST['spaceafterlastsystem'];
$spaceBeforeMetadatas = $_REQUEST['spacebeforemetadata'];
$spacings=$_REQUEST['spacing'];
$rubrictitlesizes=$_REQUEST['rubrictitlesize'];
$rubrictitlealignments=$_REQUEST['rubrictitlealignment'];
$rubrictextalignments=$_REQUEST['rubrictextalignment'];
$rubricsizes=$_REQUEST['rubricsize'];
$hymnHeaders=$_REQUEST['hymnHeader'];
$hymnsupertitles=$_REQUEST['hymnsupertitle'];
$hymnsubtitles=$_REQUEST['hymnsubtitle'];
$subsetfonts=$_REQUEST['subsetfonts'];
$publish=$_REQUEST['publish'];
$sectionJsons=$_REQUEST['sectionJson'];
if($template) {
  $template = "library/score-templates/$template";
  if(file_exists($template)) {
    $template = file_get_contents($template);
  } else {
    $template = '';
  }
}
if(!$template) {
  $template = file_get_contents('library/score-templates/default.json');
}
$template = json_decode($template,true);
$staffsize = $template['staffsize'];
if(!$staffsize) {
  $staffsize = '16';
}
$lyricsize = $template['lyricsize'];
if(!$lyricsize) {
  $lyricsize = '1.5';
}
$topmargin = $template['topmargin'];
if(!$topmargin) {
  $topmargin = '0.6';
}
$useModernFontSizes = array_key_exists('engraving-Modern',array_flip($sectionTypes));
$useModernFontSizes = false;
if($useModernFontSizes) {
  $fsizeTitle = 16;
  $fsizeGenre = 13.5;
  $fsizePsalm = 13.5;
} else {
  $fsizeTitle = 18;
  $fsizeGenre = 12;
  $fsizePsalm = 12;
}
$fsizeTitle = $template["size$fsizeTitle"];
$fsizeGenre = $template["size$fsizeGenre"];
$fsizePsalm = $template["size$fsizePsalm"];

$marginNumSize=$template['marginNumSize'];
if(!$marginNumSize || $marginNumSize == 12) {
  $marginNumSize = 12;
  $vspaceAroundGenreNumber = '0pt';
  $vspaceAroundTextAboveStaffNumber = '-5.2pt';
} else if($marginNumSize == 8) {
  $vspaceAroundGenreNumber = '-1.4pt';
  $vspaceAroundTextAboveStaffNumber = '-6.1pt';
} else {
  $vspaceAroundGenreNumber = '-1.4pt';
  $vspaceAroundTextAboveStaffNumber = '-6.1pt';
}
$vspaceAroundGenreNumber = (($marginNumSize - $fsizeGenre)/2) * 0.7;
if($vspaceAroundGenreNumber > 0) {
  $vspaceAroundGenreNumber = 0;
}
$vspaceAroundGenreNumber .= 'pt';
$marginNumBold=$template['marginNumBold'];

$marginalnumberalignment=$_REQUEST['marginalnumberalignment'];
$alignNumbersWithGenre = ($marginalnumberalignment == 'genre');
$setGaramondMarginNumbers = "\\font\\garamondMarginNumbers=GaramondPremrPro-".($marginNumBold?'Bd-':'')."lf-ly1 at {$marginNumSize}pt";
$swapmarginalnumbers=$_REQUEST['swapmarginalnumbers'];
$setGaramondHymnNumbers = "\\font\\garamondHymnNumbers=GaramondPremrPro-".($marginNumBold?'Bd-':'')."lf-ly1 at {$template['size16']}pt";
$reverseMarginPar = '\\par\\reversemarginpar';
$normalMarginPar = '\\par\\normalmarginpar';

$sectionNums = $_REQUEST['sectionnum'];

$rubrics = array();


$supertitle = applyTexBoldItalics($supertitle);
$title = applyTexBoldItalics($title);


if($footer && !preg_match('/^\s*$/',$footer)) {
  if(!preg_match('/\.txt$/',$footer)) {
    $footer .= '.txt';
  }
  $footerPath = ip_masterDir("footers/$footer");
  if($footerText && !preg_match('/^\s*$/',$footerText)) {
    $dir = dirname($footerPath);
    if(!file_exists($dir)) {
      mkdir($dir, 0777, true);
    }
    file_put_contents($footerPath, $footerText);
  } else {
    $footerText = file_get_contents($footerPath);
  }
} else {
  $footer = $footerText = '';
}
$footerText = applyTexBoldItalics($footerText);
if(preg_match('/^\s*$/',$footerText)){
  $footerText = '';
} else {
  //$footerText = "\\begin{minipage}{\\textwidth}\\fontsize{{$template['size8']}}{{$template['size8']}}\\selectfont{{$footerText}}\\end{minipage}
  $footerText = "\\fontsize{{$template['size8']}}{{$template['size8']}}\\selectfont{{$footerText}}
";
}

if(preg_match('/^\s*$/',$subtitle)) {
  if(preg_match('/^\s*$/',$title)) {
    $subtitle = '';
  } else {
    $subtitle = '{

\\vspace{12pt}

}';
  }
} else {
  $subtitle = "{
\\vspace{0.05in}\\fontsize{{$template['size12']}}{{$template['size12']}}\\selectfont\\centering\\textit{{$subtitle}}

\\vspace{12pt}

}
";
}

$dirEdition = preg_replace('/[^a-zA-Z0-9\/\\\\]+/','-',mb_strtolower($edition,'UTF-8'));
$dirEdition = str_replace('\\','/',$dirEdition);
if(preg_match('/^\s*$/',$dirEdition)) {
  $dirEdition = $edition = 'misc';
}

$odir = ip_userDir("scores/$dirEdition");

if(preg_match('/^\s*$/',$supertitle)) {
  $supertitle = '';
} else {
  $supertitle = "{\\fontsize{{$template['size14']}}{{$template['size14']}}\\selectfont\\centering\\textsc{{$supertitle}}

}\\vspace{0.0189in}";
}

$format=$_REQUEST['fmt'];

$width = $template['width'];
if(!$width) {
  $width = '4.5';
}
$pwidth = $template['pwidth'];
if(!$pwidth) {
  $pwidth = 1 + $width;
}
$vwidth = $template['vwidth'];
if(!$vwidth) {
  $vwidth = $width;
}
$bottommargin = $template['bottommargin'];
if(!$bottommargin) {
  $bottommargin = '0.6917';
}
$height = $template['height'];
if(!$height) {
  $height = '9';
}
$verseWidthDifference = ($width - $vwidth) / 2;

if($format == 'pdf-temp') {
  //$format = 'pdf';
  header("Content-type: text/plain");
  print_r($_REQUEST);
  //return;
}


$croppdf=false;
if($_REQUEST['croppdf']=='true'){
  $croppdf=true;
}
$margin = ($pwidth - $width)/2;
ini_set('magic_quotes_runtime', 0);
if($format==''){
  $format='png';
  $fmtmime='image/png';
} else {
  $fmtmime='application/pdf';
}
function replace_diacritics($matches){
  $s = '\\';
  if($matches[2]) {
    $s='`';
  } else if($matches[3]) {
    $s='\'';
  } else if($matches[4]) {
    $s='^';
  } else if($matches[5]) {
    $s='~';
  } else if($matches[6]) {
    $s='"';
  }
  return "\\$s{$matches[1]}";
}
{
  if(!$fname) {
    // try to get a filename from the shortname:
    $fname = getShortName($_REQUEST['title'],$_REQUEST['supertitle'],$_REQUEST['subtitle']);
    if(!$fname) {
      $fname = $title;
    }
  }
  $fname = normalizer_normalize($fname,Normalizer::FORM_KD);
  $title = normalizer_normalize($title,Normalizer::FORM_KD);
  $fname = preg_replace('/\p{Mn}/u', '', $fname);
  
  $outFileName = preg_replace('/\'|\W+$/','',$fname);
  $outFileName = preg_replace('/\W+/','-',$outFileName);
  if($_POST['filename']) {
    $_POST['filename'] = $outFileName;
  }
  if($outFileName == '') $outFileName = 'Untitled';
  $tmpFileName = 'tmp/' . str_replace(array('\'',' '),array('','-'),$outFileName);
  $nametex = "$tmpFileName.main.tex";
  $namelytex = "$tmpFileName.main.lytex";
  $namedvi = "$tmpFileName.main.dvi";
  $namepdf = "$tmpFileName.main.pdf";
  $namelog="$tmpFileName.main.log";
  $nameaux="$tmpFileName.main.aux";
  
  if(preg_match('/^\s*$/',$title)) {
    $title = '';
  } else {
    $title = '\\sotitle{' . str_replace("\\\\",'}\\\\*[-3.5pt]\sotitle{',preg_replace_callback('/(\p{L})(?:(\x{0300})|(\x{0301})|(\x{0302})|(\x{0303})|(\x{0308}))/u','replace_diacritics',$title)) . "\n}";
    $title = "{\\fontsize{{$fsizeTitle}}{{$fsizeTitle}}%\\fontseries{sb}
\\selectfont\\centering\\textsc{{$title}}

}

";
  }
  $nametexS = escapeshellarg($nametex);
  $namelytexS = escapeshellarg($namelytex);
  $namedviS = escapeshellarg($namedvi);
  $namepdfS = escapeshellarg($namepdf);
  $namelogS = escapeshellarg($namelog);
  $nameauxS = escapeshellarg($nameaux);
  
  $papercmd=<<<EOF
\\usepackage[papersize={{$pwidth}in,{$height}in},top={$topmargin}in,bottom={$bottommargin}in,left={$margin}in,right={$margin}in,nofoot,head=13.6pt,headsep=15pt,marginparsep=0in,marginpar={$margin}in]{geometry}
\\special{ pdf: pagesize width {$pwidth}truein height {$height}truein}
EOF;

  
  $_POST['href'] = 'http://illuminarepublications.com/editor/psalm.html';
  if($_POST['sectionID'] && count($_POST['sectionID'])>0) {
    $json = array();
    foreach($_POST as $key => $val) {
      if($key != 'gabc' && !array_key_exists($key,$sectionKeysNoID)) {
        $json[$key] = $val;
      }
    }
    foreach($engravingScoreKeys as $h => $scoreKey) {
      $tmpExtra = array();
      foreach($chantengravings as $i => $engravingSection) {
        $tmp = array();
        foreach($engravingSection as $j => $engr) {
          $tmp[] = $engr[$scoreKey];
        }
        $tmpExtra[] = $tmp;
      }
      $json[$scoreKey] = $tmpExtra;
    }
    foreach($verseScoreKeys as $h => $scoreKey) {
      $tmpExtra = array();
      foreach($verses as $i => $versesForS) {
        $tmp = array();
        foreach($versesForS as $j => $v) {
          $tmp[] = $v[$scoreKey];
        }
        $tmpExtra[] = $tmp;
      }
      $json[$scoreKey] = $tmpExtra;
    }
    if(!is_array($json['engraving'])) {
      $json['engraving'] = array();
    }
    if(!is_array($json['genrenumber'])) {
      $json['genrenumber'] = array();
    }
    foreach($sectionTypes as $i => $type) {
      if($type == 'hymn') {
        $json['engraving'][$i] = $_POST['engraving'][$i];
        $json['genrenumber'][$i] = $_POST['genrenumber'][$i];
      } else {
        if(!array_key_exists($i, $json['engraving'])) {
          $json['engraving'][$i] = '';
        }
        if(!array_key_exists($i, $json['genrenumber'])) {
          $json['genrenumber'][$i] = '';
        }
        if($type == 'antiphon-tone') {
          $json['psalmtone'][$i] = $_POST['psalmtone'][$i];
        } 
      }
    }
  } else {
    $json = $_POST;
  }
  foreach($json['sectionJson'] as $i => $js) {
    $json['sectionJson'][$i] = json_decode($js,true);
  }
    
  // Write out a template main.tex file that includes the psalms
  $fhandle = fopen($nametex, 'w');
  fwrite($fhandle, <<<EOF
\\documentclass[10pt]{article}
$papercmd
%\\usepackage{fullpage}
\\usepackage{changepage}
\\usepackage[semibold]{GaramondPremierPro}
\\usepackage{color}
\\usepackage{gregoriotex}
\\usepackage{verse}
\\usepackage[utf8]{luainputenc}
\\usepackage{graphicx}
\\usepackage{ifoddpage}
\\usepackage{fancyhdr}
\\usepackage{calc}
\\usepackage{multicol}
\\usepackage{etoolbox}
\\AtBeginEnvironment{verse}{\\raggedright}
\\setlength{\\headheight}{13.6pt}
\\pagestyle{fancy}
\\def\\SOUL@error#1{\\relax}
\\def\\PackageError#1#2#3{}
\\usepackage{soul}
\\expandafter\\def\\expandafter\\nocorrlist\\expandafter{\\nocorrlist\\?}
\\newcommand{\\?}[2]{%
  \\sbox0{\\hbox{#1}\\hbox{#2}}%
  \\sbox2{#1#2}%
  \\kern\\dimexpr\\wd2-\\wd0\\relax#2}
\\newcommand{\\fixedmarginpar}[2]{%
  \\setbox0=\\vtop{#2}\\marginzpar{\\vspace{-\\ht0}\\vspace{#1}#2}%
}
\\textwidth {$width}in
\\def\\headrulewidth{0pt}
\\begin{document}
\\font\\versiculum=Versiculum-tlf-ly1 at {$template['size12']}pt
\\font\\garamondInitial=GaramondPremrPro-tlf-ly1 at {$template['size38']}pt
\\font\\garamondTitle=GaramondPremrPro-osf-sc-ly1 at {$template['size18']}pt
$setGaramondMarginNumbers
$setGaramondHymnNumbers
\\font\\garamondMeterNumbers=GaramondPremrPro-lf-ly1 at {$template['size7']}pt
\\font\\garamondVerseNumber=GaramondPremrPro-osf-ly1 at {$template['size12']}pt
\\font\\garamondLyVerseNumber=GaramondPremrPro-lf-ly1 at {$template['size10']}pt
\\font\\garamondVerseReferenceNumber=GaramondPremrPro-lf-ly1 at {$template['size6']}pt
\\font\\garamondGenre=GaramondPremrPro-lf-ly1 at {$fsizeGenre}pt
\\font\\garamondItalicLord=GaramondPremrPro-It-lf-sc-ly1 at {$template['size12']}pt
\\font\\garamondTextLeft=GaramondPremrPro-It-lf-ly1 at {$template['size10']}pt
\\cfoot[]{}%
\\lhead[]{}%
\\chead[\\garamondMeterNumbers{\\MakeUppercase\\rightmark}]{\\garamondMeterNumbers{\\MakeUppercase\\rightmark}}%
\\setlength{\\parindent}{0in}
\\gresetstafflinefactor{13}
\\def\\greinitialformat#1{%
{\\garamondInitial #1}}
%{\\fontsize{{$template['size38']}}{{$template['size38']}}\\selectfont #1}}
\\gdef\\grelowchoralsignstyle#1{{\\fontsize{{$template['size8']}}{{$template['size8']}}\\selectfont #1}}
\\gdef\\grehighchoralsignstyle#1{{\\fontsize{{$template['size8']}}{{$template['size8']}}\\selectfont #1}}
\\def\\greabovelinestextstyle#1{\\hspace*{-5pt}\\small\\textit{#1}}

\\sodef\\sotitle{}{0.043em}{0.24em}{2em plus.1em minus.1em}
\\sodef\\SOTITLE{}{0.23em}{0.46em}{2em plus.1em minus.1em}
\\newlength{\\saveleftmargini}
\\newlength{\\vleftskipreference}
\\newlength{\\widthBelowHymnLeft}
\\newlength{\\widthBelowHymnRight}

\\setlength{\\saveleftmargini}{\\leftmargini}
\\setlength{\\leftmargini}{0.1806in}
\\setlength{\\vgap}{12bp}
%\\setlength{\\vleftskip}{4bp}
\\settowidth{\\vleftskip}{\\Vbar}
\\addtolength{\\vleftskip}{-2\\vleftskip}
\\addtolength{\\vleftskip}{\\leftmargini}

\\setlength{\\stanzaskip}{0.1975in}
%\\settowidth{\\leftmargini}{\\Vbar}
%\\addtolength{\\leftmargini}{\\vleftskip }

%\\setlength{\\footskip}{0.475in}

\\newcommand{\\tlap}[1]{\\vbox to 0pt{\\vss\\hbox{#1}}}
\\newcommand{\\dualcomment}[4][]{%
  {\\fontsize{{$template['size10']}}{{$template['size10']}}\\selectfont
  \\noindent{\\llap{\\tlap{#2\\hspace*{5.818pt}}}#3 \\hfill #4\\rlap{\\tlap{\\hspace*{5.818pt}#1}}}% empty line could be replaced by \\par
  
  \\nopagebreak\\vspace{0.25em}%
  \\relax}%
}
\\def\\grestar{%
  *%
  \\relax%
}
\\def\\Abar{%
  {\\versiculum a}%
  \\relax%
}

\\def\\Rbar{%
  {\\versiculum r}%
  \\relax%
}

\\def\\Vbar{%
  {\\versiculum v}%
  \\relax%
}
\\def\\gretranslationformat#1{%
  {\\fontsize{{$template['size10']}}{{$template['size10']}}\\selectfont\\textit{#1}%
  \\relax} %
}
\\def\\pdfliteral#1{%
  \\relax%
}
\\def\\UseAlternatePunctumCavum{%
\\gdef\\grepunctumcavumchar{\\gregoriofont\\char 75}%
\\gdef\\grelineapunctumcavumchar{\\gregoriofont\\char 76}%
\\gdef\\grepunctumcavumholechar{\\gregoriofont\\char 78}%
\\gdef\\grelineapunctumcavumholechar{\\gregoriofont\\char 80}%
\\relax %
}
$supertitle%
%{\\centering{\\garamondTitle title}
$title%
$subtitle%
\\renewcommand{\\poemtitlefont}{\\centering}
\\setlength{\\beforepoemtitleskip}{-0.125in}
\\setlength{\\afterpoemtitleskip}{-0.0875in}

EOF
);
  foreach($sectionTypes as $index => $sectionType) {
    $sectionID = $sectionIDs[$index];
    $genre = $genres[$index];
    $engraving = $engravings[$index];
    $genrenumber = $genrenumbers[$index];
    $psalmtone = $psalmtones[$index];
    $removetranslation = $removetranslations[$index];
    $spaceBeforeFirstSystem = $spaceBeforeFirstSystems[$index];
    $spaceBetweenSystems = $spaceBetweenSystemss[$index];
    $spaceAfterLastSystem = $spaceAfterLastSystems[$index];
    $spaceBeforeMetadata = $spaceBeforeMetadatas[$index];
    $lyricPadding = $lyricPaddings[$index];
    if($spaceBeforeFirstSystem == '') {
      $spaceBeforeFirstSystem = '-4pt';
    }
    if($spaceAfterLastSystem == '') {
      $spaceAfterLastSystem = '2pt';
    }
    if($spaceBeforeMetadata == '') {
      $spaceBeforeMetadata = '0pt';
    }
    $sectionJson = $sectionJsons[$index];
    if($sectionJson) {
      $sectionJson = json_decode($sectionJson,true);
    }
    if($genrenumber=='0'){
      $genrenumber='';
    }
    $genrequalifier = $genrequalifiers[$index];
    
    $acGenreQualifier = preg_split('/\\r|\\n/',file_get_contents(ip_createFile('autocompletes/genreQualifiers.txt')),NULL,PREG_SPLIT_NO_EMPTY);
    if($genrequalifier != '' && !in_array($genrequalifier,$acGenreQualifier)) {
      $acGenreQualifier[] = $genrequalifier;
      file_put_contents(ip_userDir('autocompletes/genreQualifiers.txt'),implode("\n",$acGenreQualifier));
    }
    $topspace = '\vspace{23.4pt}%space above section
';
    if($sectionType == 'space') {
      fwrite($fhandle, "
\\vspace{{$sectionID}pt}
");
    } else if($sectionType == 'pagebreak') {
      if($sectionTypes[$index-1] == 'pagebreak') {
        fwrite ($fhandle, '\hbox{}');
      }
      fwrite($fhandle, "
\\newpage
");
    } else if($sectionType == 'hairline') {
      $extraMargin = $sectionJson['margin'];
      if(!$extraMargin || $extraMargin == '') {
        $extraMargin = '0';
      }
      if($sectionJson['text']) {
        $hairlineText = $sectionJson['text'];
        $acHairlineText = preg_split('/\\r|\\n/',file_get_contents(ip_createFile('autocompletes/hairlineTexts.txt')),NULL,PREG_SPLIT_NO_EMPTY);
        if($hairlineText != '' && !in_array($hairlineText,$acHairlineText)) {
          $acHairlineText[] = $hairlineText;
          file_put_contents(ip_userDir('autocompletes/hairlineTexts.txt'),implode("\n",$acHairlineText));
        }
        $hairlineText = mb_strtolower($hairlineText);
        fwrite($fhandle, "
\\vspace{23.4pt}%space above hairline section
\\sbox0{\\fontsize{{$template['size16']}}{{$template['size16']}}\\selectfont\\textsc{{$hairlineText}}}%
\\vspace{-1.5\ht0}\\vspace{1.5pt}\\hspace{{$extraMargin}in}\\hrulefill\\hspace{1pt}\\raisebox{-0.5\ht0}{\\usebox0}\\hspace{1pt}\\hrulefill\\hspace{{$extraMargin}in}\\vspace{-0.5\ht0}\\vspace{-0.3pt}\\hrule height0pt
\\vspace{0pt}
");
      } else if($extraMargin && $extraMargin!='0') {
        fwrite($fhandle, "
\\vspace{23.4pt}%space above hairline section
\\hrule height0pt
\\hspace{{$extraMargin}in}\\hrulefill\\hspace{{$extraMargin}in}
\\hrule height0pt
\\vspace{0pt}
");        
      } else {
        fwrite($fhandle, "
\\vspace{23.4pt}%space above hairline section
\\hrule
\\vspace{0pt}
");
      }
    } else if($sectionType == 'antiphon-tone') {
      $mediant = $sectionJson['mediant'];
      $termination = $sectionJson['termination'];
      $overridetextleft = $sectionJson['overrideTextLeft'];
      if($globalOverrideTextLeft !== 'null') {
        $overridetextleft = $globalOverrideTextLeft;
      }
      $overridetextright = $sectionJson['overrideTextRight'];
      if($globalOverrideTextRight !== 'null') {
        $overridetextright = $globalOverrideTextRight;
      }
      if(is_string($overridetextleft) && $overridetextleft != '') {
        $acOverrideTextLeft = preg_split('/\\r|\\n/',file_get_contents(ip_createFile('autocompletes/overridetextleft.txt')),NULL,PREG_SPLIT_NO_EMPTY);
        if(!in_array($overridetextleft,$acOverrideTextLeft)) {
          $acOverrideTextLeft[] = $overridetextleft;
          file_put_contents(ip_userDir('autocompletes/overridetextleft.txt'),implode("\n",$acOverrideTextLeft));
        }
      }
      if(is_string($overridetextright) && $overridetextright != '') {
        $acOverrideTextRight = preg_split('/\\r|\\n/',file_get_contents(ip_createFile('autocompletes/overridetextright.txt')),NULL,PREG_SPLIT_NO_EMPTY);
        if(!in_array($overridetextright,$acOverrideTextRight)) {
          $acOverrideTextRight[] = $overridetextright;
          file_put_contents(ip_userDir('autocompletes/overridetextright.txt'),implode("\n",$acOverrideTextRight));
        }
      }
      if($psalmtone) {
        $toneName = $psalmtone;
        $psalmtone = psalmGABC($psalmtone);
        $psalmToneInfo = psalmToneInfo($psalmtone,$toneName);
        $mediant = $psalmToneInfo[0];
        $termination = $psalmToneInfo[1];
        $psalmtone = stripHeader($psalmtone);
        if(0==preg_match('/^\([cf][1-4]\)/',$psalmtone)) {
          $psalmtone = "({$psalmToneInfo['clef']})()()()$psalmtone";
        }
        $psalmtone = "initial-style: 0;\n%%\n$psalmtone";
        $tmpfname = "tmp/psalmtone-$index";
        $namegabc = "$tmpfname.gabc";
        $namegtex = "$tmpfname.tex";
        
        $tmpfnameS = escapeshellarg($tmpfname);
        $namegabcS = escapeshellarg($namegabc);
        $namegtexS = escapeshellarg($namegtex);
          
        // write out gabc
        $handle = fopen($namegabc, 'w');
        if(!$handle){
          header("Content-type: text/plain");
          echo "Unable to create file $namegabc";
          return;
        }
        fwrite($handle, "\xEF\xBB\xBF$psalmtone");
        fclose($handle);
        
// run gregorio
        exec("/home/sacredmusic/bin/$gregorioBinary $namegabcS 2>&1", $gregOutput, $gregRetVal);
        //$gregTexContent = file_get_contents($namegtex);
        //$gregTexContent = preg_replace('/(\n[^\n]*)\\\\greblockcustos([^\n]*\n)/',"\n\\greblockcustos".'$1$2',$gregTexContent);
        ////$gregTexContent = preg_replace('/(\n[^\n]*\\\\grelastofline[^\n]*\n)/',"\n",$gregTexContent);
        //$gregTexContent = preg_replace('/(\\\\greblockcustos[^.]*?\\\\gresyllable{[^}]*}{[^}]*}{[^}]*}{)0(})/','${1}1$2',$gregTexContent);
        //file_put_contents($namegtex, $gregTexContent);
        $ptWidth = $sectionJson['psalmToneWidth'];
        if(!is_numeric($ptWidth)) {
          $ptWidth = 1.7;
        }
        $extraMargins = $width - $ptWidth;
        $extraMargin = $extraMargins / 2.0;
        $includeEngraving = "
\\vspace{6pt}
\\begin{adjustwidth}{{$extraMargin}in}{{$extraMargin}in}
\\addtolength{\\hsize}{-{$extraMargins}in}
\\gresetfirstlineaboveinitial{}{}
\\setgrefactor{{$template['size17']}}

\\fontsize{{$template['size10']}}{{$template['size10']}}\\selectfont
\\setspaceafterinitial{0mm plus 0em minus 0em}
\\setspacebeforeinitial{0mm plus 0em minus 0em}
\\gretranslationheight = 0.1904in
\\grespaceabovelines=0.1044in
\\greremovetranslationspace\\greremovespaceabove\\input gsp-default.tex\\greadaptconfvalues\\gresetverticalspaces\\global\\divide\\greadditionallineswidth by \\grefactor%
\\large
\\setgretranslationcenteringscheme{1}\\UseAlternatePunctumCavum{\\includescore{\"$namegtex\"}}
\\end{adjustwidth}
\\addtolength{\\hsize}{{$extraMargins}in}
\\vspace{-12pt}
";

      } else {
        $includeEngraving = '';
      }
      $engravingPath = ip_firstFile('texts/antiphons/'.$sectionJson['text']);
      $mode = $sectionJson['mode'];
      $sigliaLeft = $sectionJson['sigliaLeft'];
      $sigliaRight = $sectionJson['sigliaRight'];
      $data = json_decode(file_get_contents($engravingPath),true);
      
      if($genrequalifier) {
        $genrequalifier = applyEmph($genrequalifier);
        $genre = $genre . " \\textit{($genrequalifier)}";
      }
      if($genre != '') {
        $genre = applyTexBoldItalics($genre);
        $genre = "
{\\noindent\\fontsize{{$fsizeGenre}}{{$fsizeGenre}}\\selectfont\\garamondGenre $genre\\nopagebreak$genrenumber\\nopagebreak
\\nopagebreak
}\\nopagebreak
";
      } else {
        $genre = '';
      }
      $textLeft = $data['text-left'];
      $textRight = $data['text-right'];
      if($overridetextleft) {
        $textLeft = $overridetextleft;
      }
      if($overridetextright) {
        $textRight = $overridetextright;
      }
      $referenceText = textRef('', $data['text'], array($mediant,$termination), false, false, false, false, true);
      $referenceText = applyTexBoldItalics($referenceText);
      $referenceText = preg_replace('/\s+([†*])/u','~$1',$referenceText);
      //$referenceText = str_replace("\n","\\\\\n",$referenceText);

      $textLeft = prepareSiglia(mb_strtolower($sigliaLeft),$textLeft);
      $textRight = prepareSiglia(mb_strtolower($sigliaRight),$textRight);
      $spaceBeforeAnnotation = '\vspace{-3pt}';
      if($textLeft != '' || $textRight != ''){
        $commentcmd = "\\dualcomment{}{\\garamondTextLeft{{$textLeft}}}{\\textit{{$textRight}}}";
        if(preg_match('/\\\\raisebox\{-4pt\}/',$textRight)) {
          $commentcmd .= '\vspace{-3pt}';
        }
        if(!$textLeft || preg_match('/^\s*$/',$textLeft)) {
          if(!$textRight || preg_match('/^\s*$/',$textRight)) {
            $spaceBeforeAnnotation = '\vspace{-4pt}';
          }
        } else {
          $spaceBeforeAnnotation = '\vspace{6pt}';
        }
      } else {
        $spaceBeforeAnnotation = '\vspace{9pt}';
      }
      $genre = escapeTeX($genre);
      $referenceText = escapeTeX($referenceText);
      fwrite($fhandle, <<<EOF
$topspace %
\\begin{minipage}{\\textwidth}
$genre
$spaceBeforeAnnotation\\vspace{0pt}\\nopagebreak%
\\nopagebreak%\\

$commentcmd
{\\fontsize{{$template['size12']}}{{$template['size12']}}\\selectfont{{$referenceText}}}
$includeEngraving
\\end{minipage}\\\\
EOF
);
    } else if($sectionType == 'rubric') {
      $rubrictitlesize = $rubrictitlesizes[$index];
      $rubrictitlealignment = $rubrictitlealignments[$index];
      $rubrictextalignment = $rubrictextalignments[$index];
      $rubricsize = $rubricsizes[$index];
      $rubric = array('title'=>$genre, 'rubric'=>$engraving, 'titlesize'=>$rubrictitlesize, 'titlealignment'=>$rubrictitlealignment, 'size'=>$rubricsize, 'textalignment'=>$rubrictextalignment);
      $rubrics[] = $rubric;
      fwrite($fhandle, texForRubricSubsection($rubric));
    } else if($sectionType == 'text') {
      $acGenre = preg_split('/\\r|\\n/',file_get_contents(ip_createFile('autocompletes/title.txt')),NULL,PREG_SPLIT_NO_EMPTY);
      if($genre != '' && !in_array($genre,$acGenre)) {
        $acGenre[] = $genre;
        file_put_contents(ip_userDir('autocompletes/title.txt'),implode("\n",$acGenre));
      }
      $newpage = '';
      if(substr($engraving,-4) != '.txt'){
        $engraving .= '.txt';
      }
      $engravingPath = ip_firstFile('texts/'.$engraving);
      $referenceText = file_get_contents($engravingPath);
      $isFormatted = (FALSE !== strpos($referenceText,'_') OR FALSE !== strpos($referenceText,'|') OR FALSE !== strpos($referenceText,"\n"));
      
      $section = array(
        'genre' => $genre,
        'genrenumber' => $genrenumber,
        'genrequalifier' => $genrequalifier,
        'engraving' => $engraving,
        'sectionID' => $sectionID,
        'sectionType' => $sectionType,
      );
      
      if($genrenumber) {
        $genrenumberReverse = $genrenumberleftright? $reverseMarginPar : $normalMarginPar;
        $genrenumber = "$genrenumberReverse{\\setbox0=\\vtop{\\garamondMarginNumbers{{$genrenumber}}}\\marginpar[\\vspace{-\\ht0}\\vspace{{$vspaceAroundGenreNumber}}\\hfill\\garamondMarginNumbers{{$genrenumber}\\hspace*{5.818pt}}]{\\vspace{-\\ht0}\\vspace{{$vspaceAroundGenreNumber}}\\garamondMarginNumbers{\\hspace*{5.818pt}{$genrenumber}}}}";
      }
      if($genrequalifier) {
        $genrequalifier = applyEmph($genrequalifier);
        $genre = $genre . " \\textit{($genrequalifier)}";
      }
      if($genre != '') {
        $genre = applyTexBoldItalics($genre);
        $genre = "
{\\fontsize{{$fsizeGenre}}{{$fsizeGenre}}\\selectfont\\noindent\\garamondGenre $genre$genrenumber
\\\\*


}";
      } else {
        $genre = '';
      }
      $sectionID = saveSection($section);
      $json['sectionID'][$index] = $sectionID;
      if($isFormatted) {
        $referenceText = applyTexBoldItalics($referenceText);
        $referenceText = str_replace("\n","\\\\\n",$referenceText);
      } else {
        $referenceText = "\\textit{{$referenceText}}";
      }
      $genre = escapeTeX($genre);
      $referenceText = escapeTeX($referenceText);
      fwrite($fhandle, <<<EOF
$newpage %
\\begin{minipage}{\\textwidth}
$topspace %
$genre
\\setlength{\\parindent}{0.1806in}
{\\fontsize{{$template['size12']}}{{$template['size12']}}\\selectfont{{$referenceText}}}
\\end{minipage}
EOF
);
      if($index != count($genres)-1 && $sectionTypes[$index+1]=='text'){
        fwrite($fhandle, '\\\\');
      }
      fwrite($fhandle, "\n");
    } else if($sectionType == 'hymn') {
      $genrenumberleftright = ($sectionJson['genrenumberleftright'] == 'left');
      $verseseparators = $sectionJson['verseseparators'];
      $extraVersesColumnLengths = $sectionJson['extraVersesColumnLengths'];
      $oneColumnExtraVerses = $sectionJson['oneColumnExtraVerses'];
      $hideMetadata = $sectionJson['hideMetadata'];
      $hideTitle = $sectionJson['hideTitle'];
      if($swapmarginalnumbers) {
        $genrenumberleftright = !$genrenumberleftright;
      }
      if($globalOverrideHeader === 'null') {
        $hymnHeader = $hymnHeaders[$index];
      } else {
        $hymnHeader = $globalOverrideHeader;
      }
      $hymnsupertitle = applyTexBoldItalics(escapeTeX(mb_strtolower($hymnsupertitles[$index],'UTF-8')));
      $hymnsubtitle = applyTexBoldItalics(escapeTeX($hymnsubtitles[$index]));
      if(preg_match('/^\s*$/',$hymnsupertitle)) {
        $hymnsupertitle = '';
      } else {
        /*$hymnsupertitle = "{\\fontsize{{$template['size14']}}{{$template['size14']}}\\selectfont\\centering\\textsc{{$hymnsupertitle}}

}\\vspace{8pt}";*/
        if($genrenumberleftright) {
          $hymnsupertitle = "\\vspace{2pt}\\raisebox{-3.25pt}{\\makebox[0pt][l]{\\garamondHymnNumbers{{$genrenumber}}}}%
\\makebox[\\textwidth][c]{\\fontsize{{$template['size14']}}{{$template['size14']}}\\selectfont\\textsc{{$hymnsupertitle}}}\\vspace{5.6pt}%
\\makebox[0pt][r]{}%";
        } else {
          $hymnsupertitle = "\\vspace{2pt}\\makebox[0pt][l]{}%
\\makebox[\\textwidth][c]{\\fontsize{{$template['size14']}}{{$template['size14']}}\\selectfont\\textsc{{$hymnsupertitle}}}%
\\raisebox{-3.25pt}{\\makebox[0pt][r]{\\garamondHymnNumbers{{$genrenumber}}}}\\vspace{5.6pt}%";
        }
      }
      if(preg_match('/^\s*$/',$hymnsubtitle)) {
        if($hideTitle && !$genrenumber) {
          $spaceAfterTheme = '';
        } else if(!$genrenumber || $hymnsupertitle) {
          $spaceAfterTheme = '\\vspace{8pt}';
        } else {
          $spaceAfterTheme = '\\\\*[8pt]';
        }
        $hymnsubtitle = '';
      } else {
        $spaceAfterTheme = '';
        if($hymnsupertitle) {
          $spaceBefore = '-6';
          $spaceAfter = '12';
        } else {
          $spaceBefore = '4';
          $spaceAfter = '10';
        }
        $hymnsubtitle = "\\vspace{{$spaceBefore}pt}{
\\vspace{2pt}\\fontsize{{$template['size12']}}{{$template['size12']}}\\selectfont\\centering\\textit{{$hymnsubtitle}}

\\vspace{{$spaceAfter}pt}

}
";
      }

      $numverses = (int)$numverseses[$index];
      if($numverses == 0) {
        $numverses = 10;
      }
      if(preg_match('/^\s*$/',$spaceBetweenSystems)) {
        $spaceBetweenSystems = '12pt plus 1fil minus 8pt';
      };
      $engravingInfo = loadLy($engraving,true);
      $engravingInfo['width'] = $width;
      $engravingInfo['raggedlast'] = ($raggedlast && $raggedlast != 0)? 't' : '';
      $engravingInfo['lyricPadding'] = $lyricPadding;
      $engravingInfo['staffsize'] = $staffsize;
      $engravingInfo['lyricsize'] = $lyricsize;
      $engravingInfo['lyricMinDistance'] = ($staffsize / 30 + 3 - 16/30);
      $engraving = getLy($engravingInfo,false,true,$numverses,$verseseparators);
      // Use the array $engravingInfo['extraverses'] and format those verses using TeX.
      $extraVerses = '';
      if($engravingInfo['extraverses']) {
        $extraVerses = "\\vspace{{$spaceAfterLastSystem}}";
        $numExtraVerses = count($engravingInfo['extraverses']);
        if($numExtraVerses > 1) {
          //for some reason, if there is only one verse, we don't want to have the new paragraph.
          $extraVerses .= '\\\\
';
        }
        $extraVerses .= "{\\fontsize{{$template['size10']}}{{$template['size12']}}\\selectfont%
";
        $startIndex = 0;
        $numInColumns = array_shift($extraVersesColumnLengths);
        $availableInColumns = ($numExtraVerses - ($numExtraVerses % 2)) / 2;
        if(is_null($numInColumns) || $numInColumns < 1 || $availableInColumns < $numInColumns) {
          $numInColumns = $availableInColumns;
        }
        if($oneColumnExtraVerses) {
          $numInColumns = 0;
        }
        while($numInColumns > 0) {
          $extraVerses .= '\begin{minipage}[t]{\textwidth / 2 - 2pt}';
          $extraVerses .= formatTexVerses(array_slice($engravingInfo['extraverses'],$startIndex,$numInColumns),
                                          array_slice($engravingInfo['extraverseNotes'],$startIndex,$numInColumns),
                                          array_slice($engravingInfo['extraverseNumbers'],$startIndex,$numInColumns),
                                          $numverses+$startIndex+1);
          $extraVerses .= '\end{minipage}\hfill\begin{minipage}[t]{\textwidth / 2 - 2pt}';
          $extraVerses .= formatTexVerses(array_slice($engravingInfo['extraverses'],$startIndex+$numInColumns,$numInColumns),
                                          array_slice($engravingInfo['extraverseNotes'],$startIndex+$numInColumns,$numInColumns),
                                          array_slice($engravingInfo['extraverseNumbers'],$startIndex+$numInColumns,$numInColumns),
                                          $numverses+$startIndex+$numInColumns+1);
          $extraVerses .= '\end{minipage}\\\\';
          $startIndex += 2*$numInColumns;

          $availableInColumns -= $numInColumns;
          $numInColumns = array_shift($extraVersesColumnLengths);
          if(is_null($numInColumns) || $numInColumns < 1 || $availableInColumns < $numInColumns) {
            $numInColumns = $availableInColumns;
          }
          if($numInColumns > 0) {
            $extraVerses .= "[8pt]\n\n";
          } else if(($numExtraVerses % 2) == 0) {
            $extraVerses .= '[4pt]';
          } else {
            $extraVerses .= '[-1.5pt]';
          }
        }
        $extraVerses .= "\n" . formatTexVerses(array_slice($engravingInfo['extraverses'],$startIndex,$numExtraVerses),
                                               array_slice($engravingInfo['extraverseNotes'],$startIndex,$numExtraVerses),
                                               array_slice($engravingInfo['extraverseNumbers'],$startIndex,$numExtraVerses),
                                               $numverses+$startIndex+1);
        $extraVerses .= "}";
      }

      if($hideTitle) {
        $title = '';
      } else {
        $title = $engravingInfo['name'];
      }
      $tune = $engravingInfo['tune-data']['name'];
      $tuneAuthor = $engravingInfo['tune-data']['author'];
      $tuneHarmonization = $engravingInfo['tune-data']['harmonization'];
      $textSource = $engravingInfo['text-data']['source'];
      $textAuthor = $engravingInfo['text-data']['author'];
      $textTranslator = $engravingInfo['text-data']['translator'];
      $textCopyright = $engravingInfo['text-data']['copyright'];
      $tuneCopyright = $engravingInfo['tune-data']['tuneCopyright'];
      $harmCopyright = $engravingInfo['tune-data']['harmCopyright'];
      $meter = $engravingInfo['tune-data']['meter'];
      if(!$meter) {
        $meter = $engravingInfo['text-data']['meter'];
      }
      if(!$hymnHeader) {
        $hymnHeader = $engravingInfo['text-data']['theme'];
      }
      if($hymnHeader) {
        $settheme = '\markright{' . escapeTeX($hymnHeader) . '}';
      } else {
        $settheme = '';
      }
      if(!$hideTitle || $genrenumber) {
        if($hymnsupertitle) {
          //if there was a supertitle, the $genrenumber has already been displayed.  We are only concerned with the title.
          $genrenumber = "
{\\fontsize{{$template['size16']}}{{$template['size16']}}\\selectfont\\centering{{$title}}

}\\vspace{8pt}";
        } else if($genrenumberleftright) {
          $genrenumber = "\\makebox[0pt][l]{\\garamondHymnNumbers{{$genrenumber}}}%
\\makebox[\\textwidth][c]{\\fontsize{{$template['size16']}}{{$template['size16']}}\\selectfont $title}%
\\makebox[0pt][r]{}%";
        } else {
          $genrenumber = "\\makebox[0pt][l]{}%
\\makebox[\\textwidth][c]{\\fontsize{{$template['size16']}}{{$template['size16']}}\\selectfont $title}%
\\makebox[0pt][r]{\\garamondHymnNumbers{{$genrenumber}}}%";
        }
      } else {
        $genrenumber = '';
      }
      $belowHymnLeftOne = '';
      $belowHymnRightOne = '';
      $belowHymnLeftTwo = '';
      $belowHymnRightTwo = '';
      $belowHymnLeftThree = '';
      $belowHymnRightThree = '';
      $belowHymnLeftFour = '';
      $belowHymnRightFour = '';
      $belowHymnOne = '';
      $belowHymnTwo = '';
      $belowHymnThree = '';
      $belowHymnFour = '';
      $belowHymn = '';
      if(!$hideMetadata) {
        if($tune) {
          $belowHymnRightOne = escapeTeX(applyTexBoldItalics($tune));
        }
        if($meter) {
          $temp = '\garamondMeterNumbers{' . escapeTeX(applyTexBoldItalics($meter)) . '}';
          if($belowHymnRightOne) {
            $belowHymnRightTwo = $temp;
          } else {
            $belowHymnRightOne = $temp;
          }
        }
        if($textSource || $textAuthor) {
          if($textSource) {
            $textText = 'TEXT: ' . reverseItalics($textSource);
            if($textAuthor) {
              $textText .= ", $textAuthor";
            }
          } else {
            $textText = "TEXT: $textAuthor";
          }
          if($textTranslator) {
            $textText .= "; Tr. $textTranslator";
          }
          if($textCopyright) {
            $textText .= ", $textCopyright";
          }
          $temp = escapeTeX(applyTexBoldItalics($textText));
          if($belowHymnLeftOne) {
            if($belowHymnLeftTwo) {
              $belowHymnLeftThree = $temp;
            } else {
              $belowHymnLeftTwo = $temp;
            }
          } else {
            $belowHymnLeftOne = $temp;
          }
        }
        if($tuneAuthor) {
          $tuneText = "TUNE: $tuneAuthor";
          if($tuneCopyright) {
            $tuneText .= ", $tuneCopyright";
          }
          if($tuneHarmonization) {
            $tuneText .= "; Harm. by $tuneHarmonization";
          }
          if($harmCopyright) {
            $tuneText .= ", $harmCopyright";
          }
          $temp = escapeTeX(applyTexBoldItalics($tuneText));
          if($belowHymnLeftOne) {
            if($belowHymnLeftTwo) {
              $belowHymnLeftThree = $temp;
            } else {
              $belowHymnLeftTwo = $temp;
            }
          } else {
            $belowHymnLeftOne = $temp;
          }
        }
        /*if($tuneHarmonization) {
          $temp = escapeTeX(applyTexBoldItalics("HARMONIZATION: $tuneHarmonization"));
          if($belowHymnLeftOne) {
            $belowHymnLeftTwo = $temp;
          } else {
            $belowHymnLeftOne = $temp;
          }
        }*/
        /*if($textTranslator) {
          $temp = escapeTeX(applyTexBoldItalics("TRANSLATOR: $textTranslator"));
          if($belowHymnLeftOne) {
            if($belowHymnLeftTwo) {
              if($belowHymnLeftThree) {
                $belowHymnLeftFour = $temp;
              } else {
                $belowHymnLeftThree = $temp;
              }
            } else {
              $belowHymnLeftTwo = $temp;
            }
          } else {
            $belowHymnLeftOne = $temp;
          }
        }*/
        $belowHymnLeft = '';
        if($belowHymnLeftOne) {
          $belowHymnLeft .= "$belowHymnLeftOne\\\\";
        }
        if($belowHymnLeftTwo) {
          $belowHymnLeft .= "[-5.5pt]

$belowHymnLeftTwo\\\\";
        }
        if($belowHymnLeftThree) {
          $belowHymnLeft .= "[-5.5pt]

$belowHymnLeftThree\\\\";
        }
        if($belowHymnLeftFour) {
          $belowHymnLeft .= "[-5.5pt]

$belowHymnLeftFour\\\\";
        }
        $belowHymnLeft .= "\n";

        $belowHymnRight = '';
        if($belowHymnRightOne) {
          $belowHymnRight .= "$belowHymnRightOne\\\\";
        }
        if($belowHymnRightTwo) {
          $belowHymnRight .= "[1.5pt]

$belowHymnRightTwo\\\\";
        }
        if($belowHymnRightThree) {
          $belowHymnRight .= "[1.5pt]

$belowHymnRightThree\\\\";
        }
        if($belowHymnRightFour) {
          $belowHymnRight .= "[1.5pt]

$belowHymnRightFour\\\\";
        }
        $belowHymnRight .= "\n";

        if($belowHymnLeftOne || $belowHymnRightOne) {
          if($belowHymnLeftOne) {
            $belowHymnLeft = "\\settowidth{\\widthBelowHymnLeft}{{$belowHymnRightOne}}
\\settowidth{\\widthBelowHymnRight}{{$belowHymnRightTwo}}
\\ifdim \\widthBelowHymnRight > \\widthBelowHymnLeft \\setlength{\\widthBelowHymnLeft}{\\widthBelowHymnRight} \\fi
%\\setlength{\\widthBelowHymnLeft}{1in}
\\setlength{\\widthBelowHymnLeft}{-\\widthBelowHymnLeft}
\\addtolength{\\widthBelowHymnLeft}{\\textwidth}
\\addtolength{\\widthBelowHymnLeft}{-24pt}
\\setlength{\\widthBelowHymnRight}{\\textwidth}
\\addtolength{\\widthBelowHymnRight}{-\\widthBelowHymnLeft}
\\parbox[t]{\\widthBelowHymnLeft}{\\hangindent=12pt $belowHymnLeft

}";
            $widthRight = '\\widthBelowHymnRight';
          } else {
            $belowHymnLeft = '';
            $widthRight = '\\textwidth';
          }
          $belowHymn = "$belowHymnLeft%
\\makebox[{$widthRight}][r]{\\parbox[t]{{$widthRight}}{\\raggedleft $belowHymnRight}}\\\\[4pt]
";
        } else {
          $belowHymn = '';
        }
      }
      $ofilename = $engravingInfo['filename'];
      if(!$ofilename) {
        $ofilename = $engravingInfo['name'];
      }
      $ofilename = normalizeFilename($ofilename);
      //$italicline = $engravingInfo['commentary'];
      //$usernotesline = $engravingInfo['user-notes'];
      //$annotation = $engravingInfo['annotation'];
      $tmpfname = str_replace('\'','',"tmp/$ofilename-$index");
      $namepdfT = "$tmpfname.pdf";
      $namely = "$tmpfname.ly";
      $nameps = "$tmpfname.ps";
      $nameSystems = "$tmpfname-systems";
      
      $namepdfTS = str_replace('\'','\\\'',$namepdfT);
      $namelyS = str_replace('\'','\\\'',$namely);
      $namepsS = str_replace('\'','\\\'',$nameps);
      
      $twidth = 72 * $width;
      $theight = 72 * $height;
      // write out ly file
      file_put_contents($namely, $engraving);
      // run lilypond
      exec("export HOME=/home/sacredmusic && /home/sacredmusic/bin/ly214 -dbackend=eps -dno-gs-load-fonts -dinclude-eps-fonts -dno-point-and-click --ps -o\"{$tmpfname}\" \"$namely\" 2>&1", $lyOutput, $lyRetVal);
      if($lyRetVal){
        @header("Content-type: text/plain");
        echo implode("\n",$lyOutput);
        return;
      }
      $sysCount = file_get_contents("$nameSystems.count");
      $includeGraphics = "";
      while($sysCount > 0) {
        $namepdfT = "$tmpfname-$sysCount.pdf";
        $nameps = "$tmpfname-$sysCount.eps";
        exec("export HOME=/home/sacredmusic && gs -q -dSAFER -dEPSCrop -dCompatibilityLevel=1.4 -dNOPAUSE -dBATCH -r1200 -sDEVICE=pdfwrite -sOutputFile=\"{$namepdfT}\" -c.setpdfwrite -f\"{$nameps}\" 2>&1", $gsOutput, $gsRetVal);
        unlink($nameps);
        $includeGraphics = "\\includegraphics{{{$tmpfname}-{$sysCount}}.pdf}%\n" . $includeGraphics;
        --$sysCount;
        if($sysCount > 0) {
          $includeGraphics = "\\vspace{{$spaceBetweenSystems}}\\\\\n" . $includeGraphics;
        }
      }
      $includeEngraving = $includeGraphics;
      fwrite($fhandle, <<<EOF
$topspace \\vskip 0\\baselineskip%
$hymnsupertitle%
$genrenumber%
$hymnsubtitle%
$settheme$spaceAfterTheme
\\vskip$spaceBeforeFirstSystem $includeEngraving$extraVerses
\\vskip$spaceBeforeMetadata
{\\fontsize{{$template['size7']}}{{$template['size7']}}\\selectfont%
$belowHymn%
}%
\\noindent
EOF
);
    } else { // section type is NOT rubric, NOT text, NOT hymn: it is an engraving section
      $isModern = preg_match('/Modern$/',$sectionType);
      $acGenre = @preg_split('/\\r|\\n/',file_get_contents(ip_createFile('autocompletes/genre.txt')),NULL,PREG_SPLIT_NO_EMPTY);
      if($genre != '' && !in_array($genre,$acGenre)) {
        $acGenre[] = $genre;
        file_put_contents(ip_userDir('autocompletes/genre.txt'),implode("\n",$acGenre));
      }
      $chantengraving = $chantengravings[$index];
      $sectionNum = $sectionNums[$index];
      $versesForSection = $verses[$index];

      
      $harmonizedpsalmtone = $harmonizedpsalmtones[$index];
      $siglia = $siglias[$index];
      $addtoengraving = $addtoengravings[$index];
      $spacing = $spacings[$index];
      $spaceBelowChant = $spaceBelowChants[$index];
      $spaceAboveChant = $spaceAboveChants[$index];
      $raggedlast = $raggedlasts[$index];
      
      if($spaceBelowChant == '') {
        $spaceBelowChant = '0';
      }
      if($spaceAboveChant == '') {
        $spaceAboveChant = '0';
      }
      if($harmonizedpsalmtone == '') {
        $harmonizedpsalmtone = '0';
      }

      $section = array(
        'genre' => $genre,
        'genrenumber' => $genrenumber,
        'genrequalifier' => $genrequalifier,
        'engraving' => remove_scorekeys($chantengraving),
        'siglia' => $siglia,
        'addtoengraving' => $addtoengraving,
        'psalmtone' => $psalmtone,
        'harmonizedpsalmtone' => $harmonizedpsalmtone,
        'spacebelowchant' => $spaceBelowChant,
        'spaceabovechant' => $spaceAboveChant,
        'sectionID' => $sectionID,
        'sectionType' => $sectionType,
        'raggedlast' => $raggedlast,
        'verses' => remove_scorekeys($versesForSection),
        'spacing' => $spacing,
        'removetranslation' => $removetranslation
      );
      $sectionID = saveSection($section);
      $json['sectionID'][$index] = $sectionID;
      if($globalOverrideHeader === 'null') {
        $engravingHeader = $sectionJson['engravingHeader'];
      } else {
        $engravingHeader = $globalOverrideHeader;
      }
      
      // Process psalm verse...
      if($harmonizedpsalmtone == '1' && $psalmtone) {
        if($isModern) {
          $modPsalmTone = $psalmtone;
        } else {
          $modPsalmTone = str_replace('.gabc','.json',$psalmtone);
        }
        $hptEngravingInfo = loadLy($modPsalmTone);
        if($hptEngravingInfo === FALSE) {
          $harmonizedpsalmtone = '';
        } else {
          $hptEngravingInfo['layout'] = 'satb';
          $hptEngravingInfo['width'] = $width - 0.015;
          $hptEngravingInfo['staffsize'] = $staffsize;
          $hptEngravingInfo['raggedlast'] = 't';
          $harmonizedpsalmtone = getLy($hptEngravingInfo,false,true);
        }
      } else {
        $harmonizedpsalmtone = '';
      }
      if($isModern) {
        if($includeverses) {
          $psalmtone = loadLy($psalmtone);
          $psalmToneInfo = lyPsalmToneInfo($psalmtone);
        }
      } else {
        $psalmtone = psalmGABC($psalmtone);
        $psalmToneInfo = psalmToneInfo($psalmtone);
      }
      if($genrequalifier) {
        $genrequalifier = applyEmph($genrequalifier);
        $genre = $genre . " \\textit{($genrequalifier)}";
      }
      $hasGenre = ($genre != '');
      $genre = applyTexBoldItalics($genre);
      if(count($chantengraving)>0) {
        $genrenumber = $chantengraving[0]['genrenumber'];
        $genrenumberleftright = $chantengraving[0]['genrenumberleftright'] != 'right';
        if($swapmarginalnumbers) {
          $genrenumberleftright = !$genrenumberleftright;
        }
      } else {
        $genrenumber = '';
      }
      if($genrenumber != '') {
        $genrenumberReverse = $genrenumberleftright? $reverseMarginPar : $normalMarginPar;
        $genrenumber = "$genrenumberReverse{\\setbox0=\\vtop{\\garamondMarginNumbers{{$genrenumber}}}\\marginpar[\\vspace{-\\ht0}\\vspace{{$vspaceAroundGenreNumber}}\\hfill\\garamondMarginNumbers{{$genrenumber}\\hspace*{5.818pt}}]{\\vspace{-\\ht0}\\vspace{{$vspaceAroundGenreNumber}}\\garamondMarginNumbers{\\hspace*{5.818pt}{$genrenumber}}}}";
      }
      if($hasGenre) {
        $includeGenreNumber = $alignNumbersWithGenre? $genrenumber : '';
        $genre = "
{\\noindent\\fontsize{{$fsizeGenre}}{{$fsizeGenre}}\\selectfont\\garamondGenre $genre\\nopagebreak$includeGenreNumber\\nopagebreak
\\nopagebreak
}\\nopagebreak
";
      } else {
        $genre = '';
      }
      $psalmverseTex = "\\vspace{0pt}\\fontsize{{$template['size12']}}{{$template['size14']}}\\selectfont ";
      if(!$versesForSection) $versesForSection = Array();
      $twocolumns = $sectionJson['twoColumnVerses'];
      foreach($versesForSection as $verseNum => $verse) {
        if($verse['type']=='rubric') {
          $psalmverseTex .= texForRubricSubsection($verse);
          continue;
        } else if($verse['type']=='space') {
          $spaceText = $verse['space'];
          $psalmverseTex .= "
\\vspace{{$spaceText}pt}
";
          continue;
        }
        $verselabel = $verse['verselabel'];
        $pagebreakbeforeverse = $verse['pagebreakbeforeverse'];
        $psalmtitle = $verse['psalmtitle'];
        $versesource = $verse['versesource'];
        $versefile = $verse['versefile'];
        $psalmverse = $verse['psalmverse'];
        $markverses = $verse['markverses'];
        $notateverses = $verse['notateverses'];
        $markpenultimateaccent = $verse['markpenultimateaccent'];
        $allowPageBreaksMidVerse = $verse['allowpagebreaksmidverse'];
        $glorybe = $verse['glorybe'];
        if($twocolumns) {
          $beginColumns = '\begin{multicols}{2}';
          $endColumns = '\end{multicols}';
        } else {
          $beginColumns = '';
          $endColumns = '';
        }

        // Put some extra space between verses.
        $slightVerticalSpace = ($twocolumns || $allowPageBreaksMidVerse)? $slightVerticalSpaceAllowPageBreak : $slightVerticalSpaceNoPageBreak;
        if($pagebreakbeforeverse && $pagebreakbeforeverse!='0') {
          $pagebreakbeforeverse = '\newpage%page break before verse';
        } else {
          $pagebreakbeforeverse = '\vspace{8pt}%space between verses';
        }
          $psalmverseTex .= "$pagebreakbeforeverse
";

        if($verselabel != '') {
          $acVerseLabel = preg_split('/\\r|\\n/',file_get_contents(ip_createFile('autocompletes/verselabel.txt')),NULL,PREG_SPLIT_NO_EMPTY);
          if(!in_array($verselabel,$acVerseLabel)) {
            $acVerseLabel[] = $verselabel;
            file_put_contents(ip_userDir('autocompletes/verselabel.txt'),implode("\n",$acVerseLabel));
          }
        }
        if($versesource == '~') {
          $versesource = "~/$versefile";
        }
        if($includeverses) {
          if(!$psalmverse || preg_match('/^\s*$/',$psalmverse)) {
            $psalmverse = psalmRef($psalmtitle, $psalmToneInfo, $glorybe, 'Psalm', $versesource, $markpenultimateaccent, true, $notateverses);
          } else {
            $psalmverse = preg_replace('/\s+$/D', '', $psalmverse);
            if($glorybe) {
              $psalmverse .= "\n\n" . gloryBe($psalmToneInfo);
            }
            if(!$markpenultimateaccent) {
              $psalmverse = removeEscapedAcuteAccents($psalmverse);
            }
          }
        }
        
        if(preg_match('/^\s*$/',$verselabel)) {
          $verselabel = '';
        } else {
          $verselabel = applyTexBoldItalics('_'.$verselabel.'_');
        }
        $psalmtitle = applyTexBoldItalics($psalmtitle);
        if(preg_match('/^\s*$/',$psalmtitle)) {
          $psalmtitle = '';
        }
        $titleline = '%\\begin{samepage}
';
        $needToEndSamePage = false;
        //if($notateverses) {
        //  $titleline = '';
        //} else {
        //  $titleline = '';//"\\vspace{-0.138in}\n";
        //}
        if($psalmtitle || $verselabel) {
          $titleline .= "\\noindent
\\makebox[0pt][l]{{$verselabel}}%
\\makebox[\\textwidth][c]{{$psalmtitle}}%
\\makebox[0pt][r]{\\texttt{}}";//\\\\*[0.138in]
        } else {
          $titleline .= '\\vspace{-10pt}'; //without this, there is too much space above the verse when it has no title.
        }
        $flagverse = '\\flagverse{}';
        $numberverses = false;
        $referencenumberverses = false;
        $renewFlagVerse = '\\renewcommand{\\flagverse}[1]{\\hskip-\\vleftskip\\llap{#1}\\hskip\\vleftskip\\ignorespaces}';
        if($markverses) {
          if($markverses == 'numbers') {
            $versenumber = 1;
            $numberverses = true;
            $flagverse = "\\flagverse{\\garamondVerseNumber{{$versenumber}.}}";
          } else if($markverses == 'referenceNumbers') {
            $renewFlagVerse = '\\renewcommand{\\flagverse}[1]{\\vskip-4pt\\nopagebreak\\hskip-\\vleftskipreference\\llap{#1}\\hskip\\vleftskipreference\\ignorespaces\\nopagebreak\\vskip-24.25pt\\nopagebreak}';
            $referencenumberverses = true;
          } else if($markverses == 'versicle') {
            $flagverse = '\\flagverse{\\Vbar}';
          }
        }
        if($includeverses && $psalmverse && !preg_match('/^\s*$/',$psalmverse)) {
          if($notateverses) {
            $versefilename = "$tmpFileName-$index";
            $versefilenameGabc = escapeshellarg("$versefilename.gabc");
            $versefilenameGtex = "$versefilename.tex";
            $args = Array();
            $args[] = escapeshellarg($psalmToneInfo['gabc'][0]);
            $args[] = escapeshellarg($psalmToneInfo['gabc'][1]);
            $args[] = escapeshellarg($psalmverse);
            $args[] = $versefilenameGabc;
            $args = implode(' ',$args);
            //run node.js script:
            exec("/home/sacredmusic/bin/node applyPsalmTone.js $args 2>&1", $nodeOutput, $nodeRetVal);
            if($nodeRetVal != 0) {
              echo implode('<br/>',$nodeOutput);
            }
            //run Gregorio:
            exec("/home/sacredmusic/bin/$gregorioBinary $versefilenameGabc 2>&1", $gregOutput, $gregRetVal);
            //$gregTexContent = file_get_contents($versefilenameGtex);
            //$gregTexContent = preg_replace('/(\n[^\n]*)\\\\greblockcustos([^\n]*\n)/',"\n\\greblockcustos".'$1$2',$gregTexContent);
            //$gregTexContent = preg_replace('/(\\\\greblockcustos[^.]*?\\\\gresyllable{[^}]*}{[^}]*}{[^}]*}{)0(})/','${1}1$2',$gregTexContent);
            //file_put_contents($versefilenameGtex, $gregTexContent);
            $includeEngraving = "\\setgretranslationcenteringscheme{1}\\UseAlternatePunctumCavum{\\includescore{\"$namegtex\"}}";
            $psalmverseTex .= "$titleline\n\\UseAlternatePunctumCavum{\\includescore{\"$versefilenameGtex\"}}%\n%\\end{samepage}\n";
            $needToEndSamePage = false;
          } else {
            $lines = explode("\n", $psalmverse);
            $val = $flagverse;
            $indentpattern = array();
            $v = false;
            $forceIndent = false;
            for($i=0; $i < count($lines); ++$i) {
              $line = preg_replace('/\s+([†*])/u','~$1',$lines[$i]);
              $nextLine = $lines[1 + $i];
           
              if(preg_match('/^[ \t\r]*$/',$line)) {
                if($needToEndSamePage) {
                  $needToEndSamePage = false;
                  $val .= "\n\\end{samepage}";
                }
                if($v) {
                  if($numberverses) {
                    $versenumber++;
                    $flagverse = "\\flagverse{\\garamondVerseNumber{{$versenumber}.}}";
                  }
                  $val .= "\n\n$flagverse";
                  $v = false;
                }
              } else {
                $forceIndentNextTime = false;
                $val .= "\n" . $line . '\\\\';
                $add = (!$nextLine || preg_match('/^\s*$/',$nextLine))? '!' : 
                      (($nextLine && preg_match('/^\S/',$nextLine))? $slightVerticalSpace : '*');
                if(preg_match('/†\s*$/',$line)) {
                  $forceIndentNextTime = true;
                  $val .= '*';
                } else {
                  $val .= $add;
                  if($format == 'pdf-temp') {
                    echo "   : $line\n";
                    echo "$i($add): $nextLine\n";
                  }
                }
                $v = true;
                $indentpattern[] = ($forceIndent || preg_match('/^\\s/',$line))? 1 : 0;
                $forceIndent = $forceIndentNextTime;
              }
            }
            $indentpattern = '\\indentpattern{' . implode($indentpattern) . '}';
            $val = applyTexBoldItalics($val);
            // replace LORD and L\r{O}RD to be small caps.
            $val = preg_replace('/\bL(\\\\[r\'`][ {])?O(})?RD\b/','\\textsc{l$1o$2rd}',$val);
            $val = preg_replace('/(\\\\textit{[^\\\\}]*)\\\\textsc{([^}]*)}/i','$1{\\garamondItalicLord $2}',$val);
            $val = preg_replace('/\\[(\\d+)\\]/', $referencenumberverses? "\\settowidth{\\vleftskipreference}{\\garamondVerseReferenceNumber{\$1}}
\\addtolength{\\vleftskipreference}{-2\\vleftskipreference}
\\addtolength{\\vleftskipreference}{\\leftmargini}
\\flagverse{\\garamondVerseReferenceNumber{\$1}}\n" : "",$val);
            $psalmverseTex .= "\\widowpenalties 1 10000
\\raggedbottom
$titleline$renewFlagVerse
$beginColumns
\\begin{verse}
\\begin{adjustwidth}{{$verseWidthDifference}in}{{$verseWidthDifference}in}
\\begin{patverse}
%\\setlength{\\baselineskip}{0in}
$indentpattern
$val
\\end{patverse}
\\end{adjustwidth}
\\end{verse}
$endColumns
\\widowpenalties 0
";
            if($needToEndSamePage) {
              $psalmverseTex .= "\\end{samepage}\n";
            }
          }
        } else {
          $psalmverseTex = '\vspace{8pt}%space instead of verses
';
        }
      }

      if(preg_match('/^\s*$/',$spaceBetweenSystems)) {
        $spaceBetweenSystems = '12pt plus 6pt minus 8pt';
      };
      if($harmonizedpsalmtone) {
        $ofilename = $hptEngravingInfo['filename'];
        //$italicline = $hptEngravingInfo['commentary'];
        //$usernotesline = $hptEngravingInfo['user-notes'];
        //$annotation = $hptEngravingInfo['annotation'];
        $tmpfname = str_replace('\'','',"tmp/$ofilename-$index");
        $namepdfT = "$tmpfname.pdf";
        $namely = "$tmpfname.ly";
        $nameps = "$tmpfname.ps";
        $nameSystems = "$tmpfname-systems";
        
        $namepdfTS = str_replace('\'','\\\'',$namepdfT);
        $namelyS = str_replace('\'','\\\'',$namely);
        $namepsS = str_replace('\'','\\\'',$nameps);
        
        $twidth = 72 * $width;
        $theight = 72 * $height;
        // write out ly file
        file_put_contents($namely, $harmonizedpsalmtone);
        // run lilypond
        //exec("export HOME=/home/sacredmusic && /home/sacredmusic/bin/ly214 -dno-point-and-click --ps -o\"$tmpfname\" \"$namely\" 2>&1", $lyOutput, $lyRetVal);
        exec("export HOME=/home/sacredmusic && /home/sacredmusic/bin/ly214 -dbackend=eps -dno-gs-load-fonts -dinclude-eps-fonts -dno-point-and-click --ps -o\"{$tmpfname}\" \"$namely\" 2>&1", $lyOutput, $lyRetVal);
        if($lyRetVal){
          @header("Content-type: text/plain");
          echo implode("\n",$lyOutput);
          return;
        }
        $sysCount = file_get_contents("$nameSystems.count");
        $includeGraphics = "";
        while($sysCount > 0) {
          $namepdfT = "$tmpfname-$sysCount.pdf";
          $nameps = "$tmpfname-$sysCount.eps";
          exec("export HOME=/home/sacredmusic && gs -q -dSAFER -dEPSCrop -dCompatibilityLevel=1.4 -dNOPAUSE -dBATCH -r1200 -sDEVICE=pdfwrite -sOutputFile=\"{$namepdfT}\" -c.setpdfwrite -f\"{$nameps}\" 2>&1", $gsOutput, $gsRetVal);
          unlink($nameps);
          $includeGraphics = "\\includegraphics{{{$tmpfname}-{$sysCount}}.pdf}\n" . $includeGraphics;
          --$sysCount;
          if($sysCount > 0) {
            $includeGraphics = "\\linebreak\\vspace{1in plus4mm minus5mm}\n" . $includeGraphics;
          }
        }
        // Run gs on it.
        //exec("export HOME=/home/sacredmusic && gs -q -dSAFER -dDEVICEWIDTHPOINTS=$twidth -dDEVICEHEIGHTPOINTS=$theight -dCompatibilityLevel=1.4 -dNOPAUSE -dBATCH -r1200 -sDEVICE=pdfwrite -dEmbedAllFonts=true -sOutputFile=\"{$namepdfT}\" -c.setpdfwrite -f\"{$nameps}\" 2>&1", $gsOutput, $gsRetVal);
        //if($gsRetVal){
        //  @header("Content-type: text/plain");
        //  echo implode("\n",$lyOutput);
        //  echo "\n\n";
        //  echo implode("\n",$gsOutput);
        //  return;
        //}
        // crop PDF
        //exec("pdfcrop $namepdfTS $namepdfTS 2>&1", $croppdfOutput, $croppdfRetVal);
        //if($croppdfRetVal){
        //  header("Content-type: text/plain");
        //  echo implode("\n",$croppdfOutput);
        //  return;
        //}
        //$includeHarmonizedPsalmTone = "\\begin{center}\\includegraphics{{{$tmpfname}}.pdf}\\end{center}";
        //$includeHarmonizedPsalmTone = "\\begin{center}\\input{{$nameSystems}.tex}\\end{center}";
        $includeHarmonizedPsalmTone = "\\begin{center}\\vspace{12pt plus 6pt minus 8pt}$includeGraphics\\end{center}";
      } else {
        $includeHarmonizedPsalmTone = '';
      }
      
      $engravingTeX = '';
      foreach($chantengraving as $chanti => $curEngraving) {
        $engravinglabel = $curEngraving['engravinglabel'];
        $spacing = $curEngraving['spacing'];
        $engraving = $curEngraving['engraving'];
        $siglia = $curEngraving['siglia'];
        $siglia = mb_strtolower(removeOverridenSiglia($siglia, $overrideSiglia),'UTF-8');
        $addtoengraving = $curEngraving['addtoengraving'];
        $removetranslation = $curEngraving['removetranslation'];
        $overridetextleft = $curEngraving['overridetextleft'];
        if($globalOverrideTextLeft !== 'null') {
          $overridetextleft = $globalOverrideTextLeft;
        }
        $overridetextright = $curEngraving['overridetextright'];
        if($globalOverrideTextRight !== 'null') {
          $overridetextright = $globalOverrideTextRight;
        }
        if(is_string($overridetextleft) && $overridetextleft != '') {
          $acOverrideTextLeft = preg_split('/\\r|\\n/',file_get_contents(ip_createFile('autocompletes/overridetextleft.txt')),NULL,PREG_SPLIT_NO_EMPTY);
          if(!in_array($overridetextleft,$acOverrideTextLeft)) {
            $acOverrideTextLeft[] = $overridetextleft;
            file_put_contents(ip_userDir('autocompletes/overridetextleft.txt'),implode("\n",$acOverrideTextLeft));
          }
        }
        if(is_string($overridetextright) && $overridetextright != '') {
          $acOverrideTextRight = preg_split('/\\r|\\n/',file_get_contents(ip_createFile('autocompletes/overridetextright.txt')),NULL,PREG_SPLIT_NO_EMPTY);
          if(!in_array($overridetextright,$acOverrideTextRight)) {
            $acOverrideTextRight[] = $overridetextright;
            file_put_contents(ip_userDir('autocompletes/overridetextright.txt'),implode("\n",$acOverrideTextRight));
          }
        }
        $spaceAboveChant = $curEngraving['spaceabovechant'];
        $spaceBelowChant = $curEngraving['spacebelowchant'];
        $pageBreakBeforeEngraving = $curEngraving['pagebreakbeforeengraving'];
        if($spaceAboveChant == '') $spaceAboveChant = '0';
        if($spaceBelowChant == '') $spaceBelowChant = '0';
        if($chanti == 0 && $hasGenre && $alignNumbersWithGenre) {
          $genrenumber = '';
        } else {
          $genrenumber = $curEngraving['genrenumber'];
          $genrenumberleftright = $curEngraving['genrenumberleftright'] != 'right';
          if($swapmarginalnumbers) {
            $genrenumberleftright = !$genrenumberleftright;
          }
        }
        if($engravinglabel != '') {
          $acEngravingLabel = preg_split('/\\r|\\n/',file_get_contents(ip_createFile('autocompletes/engravinglabel.txt')),NULL,PREG_SPLIT_NO_EMPTY);
          if(!in_array($engravinglabel,$acEngravingLabel)) {
            $acEngravingLabel[] = $engravinglabel;
            file_put_contents(ip_userDir('autocompletes/engravinglabel.txt'),implode("\n",$acEngravingLabel));
          }
        }

        if($isModern) {
          //$spaceBelowChant = '0.125';
          $localSpaceBetweenSystems = $curEngraving['spacebetweensystems'];
          if(preg_match('/^\s*$/',$localSpaceBetweenSystems)) {
            $localSpaceBetweenSystems = '12pt plus 6pt minus 8pt';
          };
          $spaceBetweenSystems = $localSpaceBetweenSystems;
          $engravingInfo = loadLy($engraving);
          if($includeverses) {
            //$spaceBelowChant = '0';
            if(!$harmonizedpsalmtone) {
              $engravingInfo['sop'] .= ' ' . $addtoengraving . ' \\relative c\' { ' . $psalmtone['sop'] . ' } ';
              $engravingInfo['ten'] .= ' ' . $addtoengraving . ' \\relative c\' { ' . $psalmtone['ten'] . ' } ';
              $engravingInfo['alt'] .= ' ' . $addtoengraving . ' \\relative c\' { ' . $psalmtone['alt'] . ' } ';
              $engravingInfo['bas'] .= ' ' . $addtoengraving . ' \\relative c\' { ' . $psalmtone['bas'] . ' } ';
            }
          }
          $engravingInfo['width'] = $width - 0.015;
          $engravingInfo['raggedlast'] = $curEngraving['raggedlast']? 't' : '';
          $engravingInfo['staffsize'] = $staffsize;
          $engravingInfo['lyricsize'] = $lyricsize;
          $engravingInfo['lyricMinDistance'] = ($staffsize / 30 + 3 - 16/30);
          $engraving = getLy($engravingInfo,false,true);
          $ofilename = $engravingInfo['filename'];

          $usernotesline = is_string($overridetextleft)? $overridetextleft : $engravingInfo['user-notes'];
          $italicline = is_string($overridetextright)? $overridetextright : $engravingInfo['commentary'];
          $annotation = $engravingInfo['annotation'];
          $tmpfname = str_replace('\'','',"tmp/$ofilename-$index");
          $namepdfT = "$tmpfname.pdf";
          $namely = "$tmpfname.ly";
          $nameps = "$tmpfname.ps";
          $nameSystems = "$tmpfname-systems";
          
          $namepdfTS = str_replace('\'','\\\'',$namepdfT);
          $namelyS = str_replace('\'','\\\'',$namely);
          $namepsS = str_replace('\'','\\\'',$nameps);
          
          $twidth = 72 * $width;
          $theight = 72 * $height;
          // write out ly file
          file_put_contents($namely, $engraving);
          // run lilypond
          exec("export HOME=/home/sacredmusic && /home/sacredmusic/bin/ly214 -dbackend=eps -dno-gs-load-fonts -dinclude-eps-fonts -dno-point-and-click --ps -o\"{$tmpfname}\" \"$namely\" 2>&1", $lyOutput, $lyRetVal);
          if($lyRetVal){
            @header("Content-type: text/plain");
            echo implode("\n",$lyOutput);
            return;
          }
          $includeGraphics = "";
          if(file_exists("$nameSystems.count")) {
            $sysCount = file_get_contents("$nameSystems.count");
            while($sysCount > 0) {
              $namepdfT = "$tmpfname-$sysCount.pdf";
              $nameps = "$tmpfname-$sysCount.eps";
              exec("export HOME=/home/sacredmusic && gs -q -dSAFER -dEPSCrop -dCompatibilityLevel=1.4 -dNOPAUSE -dBATCH -r1200 -sDEVICE=pdfwrite -sOutputFile=\"{$namepdfT}\" -c.setpdfwrite -f\"{$nameps}\" 2>&1", $gsOutput, $gsRetVal);
              unlink($nameps);
              $includeGraphics = "\\includegraphics{{{$tmpfname}-{$sysCount}}.pdf}\n" . $includeGraphics;
              --$sysCount;
              if($sysCount > 0) {
                $includeGraphics = "\\vspace{{$localSpaceBetweenSystems}}\\linebreak\n" . $includeGraphics;
              }
            }
          }
          // Run gs on it.
          //exec("export HOME=/home/sacredmusic && gs -q -dSAFER -dDEVICEWIDTHPOINTS=$twidth -dDEVICEHEIGHTPOINTS=$theight -dCompatibilityLevel=1.4 -dNOPAUSE -dBATCH -r1200 -sDEVICE=pdfwrite -dEmbedAllFonts=true -sOutputFile=\"{$namepdfT}\" -c.setpdfwrite -f\"{$nameps}\" 2>&1", $gsOutput, $gsRetVal);
          //if($gsRetVal){
          //  @header("Content-type: text/plain");
          //  echo implode("\n",$lyOutput);
          //  echo "\n\n";
          //  echo implode("\n",$gsOutput);
          //  return;
          //}
          // crop PDF
          //exec("pdfcrop $namepdfTS $namepdfTS 2>&1", $croppdfOutput, $croppdfRetVal);
          //if($croppdfRetVal){
          //  header("Content-type: text/plain");
          //  echo implode("\n",$croppdfOutput);
          //  return;
          //}
          //$includeEngraving = "\\includegraphics{{{$tmpfname}}.pdf}";
          //$includeEngraving = "\\input{{$nameSystems}.tex}";
          $includeEngraving = $includeGraphics;
        } else { //!$isModern
          $engraving = engravingGABC($engraving);
          if($removetranslation) {
            $engraving = preg_replace('/((?:$|\))[^(]*)\[[^]]+\]/','$1',$engraving);
          }
          $clef = preg_match_all('/((cb?|f)([1-4]))/',$engraving,$matches);
          if($clef) {
            $clef = $matches[1];
            $clef = $clef[count($clef)-1];
          } else {
            $clef = 'c4';
          }
          if($includeverses) { // && !$notateverses) { // had to comment this out because notateverses is now at the verse level, rather than the section level.
            $gabc = $engraving . $addtoengraving;
            if(!$harmonizedpsalmtone) {
              $gabc = $gabc . "\n" . translateGABC($psalmtone,$clef);
            }
          } else {
            $gabc = $engraving;
          }
          $header = gabcHeader($engraving);
          $ofilename = $header['name'];
          if($ofilename=='') {
            $ofilename='Untitled';
          }
        
          $tmpfname = "tmp/$ofilename-$index-$chanti";
          $namegabc = "$tmpfname.gabc";
          $namegtex = "$tmpfname.tex";
          
          $tmpfnameS = escapeshellarg($tmpfname);
          $namegabcS = escapeshellarg($namegabc);
          $namegtexS = escapeshellarg($namegtex);
          
          $spacingcmd = '';
          if($spacing!='vichi' && $spacing!='smith') {
            $spacing = 'default';
          }
          if(!$includeverses) {
            $spacing = 'vichi';
          }
          //$spacingcmd = "\GreLoadSpaceConf{{$spacing}}";
          $spacingcmd = "\\greremovetranslationspace\\greremovespaceabove\\input gsp-$spacing.tex\\greadaptconfvalues\\gresetverticalspaces\\global\\divide\\greadditionallineswidth by \\grefactor%";
          $usernotesline = is_string($overridetextleft)? $overridetextleft : $header['user-notes'];
          $italicline = is_string($overridetextright)? $overridetextright : $header['commentary'];
          $annotation = $header['annotation'];
    
// write out gabc
          $handle = fopen($namegabc, 'w');
          if(!$handle){
            header("Content-type: text/plain");
            echo "Unable to create file $namegabc";
            return;
          }
          fwrite($handle, "\xEF\xBB\xBF$gabc");
          fclose($handle);
          
// run gregorio
          exec("/home/sacredmusic/bin/$gregorioBinary $namegabcS 2>&1", $gregOutput, $gregRetVal);
          $gregTexContent = file_get_contents($namegtex);
          $gregTexContent = preg_replace('/(\n[^\n]*)\\\\greblockcustos([^\n]*\n)/',"\n\\greblockcustos".'$1$2',$gregTexContent);
          ////$gregTexContent = preg_replace('/(\n[^\n]*\\\\grelastofline[^\n]*\n)/',"\n",$gregTexContent);
          $gregTexContent = preg_replace('/(\\\\greblockcustos[^.]*?\\\\gresyllable{[^}]*}{[^}]*}{[^}]*}{)0(})/','${1}1$2',$gregTexContent);
          file_put_contents($namegtex, $gregTexContent);
          $includeEngraving = "\\setgretranslationcenteringscheme{1}\\UseAlternatePunctumCavum{\\includescore{\"$namegtex\"}}";
        }
        
        $commentcmd = '\dualcomment{}{}{}';
        $spaceBeforeAnnotation = '\vspace{-3pt}';
        $italicline = prepareSiglia($siglia,$italicline);
        if($usernotesline != '' || $italicline != ''){
          $commentcmd = "\\dualcomment{}{\\garamondTextLeft{{$usernotesline}}}{\\textit{{$italicline}}}";
          if(preg_match('/\\\\raisebox\{-4pt\}/',$italicline)) {
            $commentcmd .= '\vspace{-3pt}';
          }
          if(!$usernotesline || preg_match('/^\s*$/',$usernotesline)) {
            if(!$italicline || preg_match('/^\s*$/',$italicline)) {
              $spaceBeforeAnnotation = '\vspace{-4pt}';
            }
          } else {
            $spaceBeforeAnnotation = '\vspace{6pt}';
          }
        } else {
          $spaceBeforeAnnotation = '';
        }
        $annotcmd = '';
        $annotsuffix='';
        if($annotation != '') {
          if(preg_match('/[a-g]\d?\*?\s*$/',$annotation, $match)){
            $annotsuffix=$match[0];
            $annotation = substr($annotation,0,strlen($annotation) - strlen($annotsuffix));
          }
          $annotation = preg_replace_callback(
            '/\b[A-Z\d]+\b/',
            create_function(
              '$matches',
              'return strtolower($matches[0]);'
            ),
            $annotation
          );
          $annothelper = "\\fontsize{{$template['size12']}}{{$template['size12']}}\\selectfont{\\textsc{{$annotation}}$annotsuffix}";
          $annotcmd = "\\gresetfirstlineaboveinitial{{$annothelper}}{{$annothelper}}";
        }
        $annotwidthcmd=<<<EOF
\\setspaceafterinitial{2.2mm plus 0em minus 0em}
\\setspacebeforeinitial{2.2mm plus 0em minus 0em}
EOF;
        $spaceBetween = strlen($engravingTeX)==0?'':'\\vspace{4pt}
';
        if(strlen($engravinglabel)>0) $engravinglabel = applyTexBoldItalics($engravinglabel);
        if(strlen($genrenumber)>0) {
          $genrenumberReverse = $genrenumberleftright? $reverseMarginPar : $normalMarginPar;
        }
        if($genrenumber) {
          if($alignNumbersWithGenre) {
            $textabovestaffNumber = '';
            $genrenumber = "$genrenumberReverse{\\setbox0=\\vtop{\\garamondMarginNumbers{{$genrenumber}}}\\marginpar[\\vspace{-\\ht0}\\vspace{{$vspaceAroundGenreNumber}}\\hfill\\garamondMarginNumbers{{$genrenumber}\\hspace*{5.818pt}}]{\\vspace{-\\ht0}\\vspace{{$vspaceAroundGenreNumber}}\\garamondMarginNumbers{\\hspace*{5.818pt}{$genrenumber}}}}";
          } else {
            $textabovestaffNumber = '';
            $tempStr = "\\garamondMarginNumbers{{$genrenumber}}";
            $tempStr = $genrenumberleftright? "{{$tempStr}}": "[$tempStr]{}";
            $commentcmd = str_replace('\\dualcomment{}', "\\dualcomment$tempStr", $commentcmd);
            $genrenumber = '';
          }
        } else {
          $textabovestaffNumber = '';
        }
        if(strlen($engravinglabel)>0 || strlen($genrenumber)>0) {
          $extraVspace = $chanti == 0? '\vspace{4pt}' : '';
          $engravinglabel = "
$extraVspace{\\noindent\\fontsize{{$fsizeGenre}}{{$fsizeGenre}}\\selectfont\\garamondGenre{{$engravinglabel}\\nopagebreak{$genrenumber}}\\nopagebreak
\\nopagebreak
}\\nopagebreak
";
        }
        $pageBreak = $pageBreakBeforeEngraving? '\newpage':'';
        $engravingTeX .= "$spaceBetween$pageBreak$engravinglabel$spaceBeforeAnnotation\\vspace{{$spaceAboveChant}pt}\\nopagebreak%
$annotcmd \\nopagebreak%\\

$commentcmd
\\nopagebreak\\setgrefactor{{$template['size17']}}
{\\fontsize{{$template['size10']}}{{$template['size10']}}\\selectfont
$annotwidthcmd
\\gretranslationheight = 0.1904in
\\grespaceabovelines=0.1044in
$spacingcmd
%\\fontsize{{$fsizePsalm}}{{$fsizePsalm}}\\selectfont
\\large
\\nopagebreak$includeEngraving
\\vspace{{$spaceBelowChant}pt}%
";
      }
      if(!$engravingTeX) {
        $engravingTeX = '{';
      }
      //SECTIONS...
      $genre = escapeTeX($genre);
      if($engravingHeader) {
        $settheme = '\markright{' . escapeTeX($engravingHeader) . '}';
      } else {
        $settheme = '\markright{}';
      }
      $psalmverseTex = escapeTeX($psalmverseTex);
      fwrite($fhandle, <<<EOF
$topspace %
$genre$settheme$engravingTeX
$includeHarmonizedPsalmTone%
$psalmverseTex
}
EOF
    );
  }
}
if(!file_exists($odir)) {
  mkdir($odir, 0777, true);
}
$handle = fopen("$odir/$outFileName.json", 'w');
if(!$handle){
  header("Content-type: text/plain");
  echo "Unable to create file $odir/$outFileName.json";
  return;
}
if($rubrics) {
  $json['rubrics'] = $rubrics;
}
fwrite($handle,json_encode($json));
fclose($handle);
$footerText = escapeTeX($footerText);
fwrite($fhandle, <<<EOF
\\vfill$footerText\\end{document}
EOF
);
  fclose($fhandle);
// Run lualatex.
exec("export HOME=/home/sacredmusic && export TEXMFCNF=.: && /home/sacredmusic/bin/lualatex -output-directory=tmp -interaction=nonstopmode $nametexS 2>&1", $lualatexOutput, $lualatexRetVal);
// Run lamed on it.
//  exec("export TEXMFCONFIG=/home/sacredmusic/texmf && export TEXMFHOME=/home/sacredmusic/texmf && export HOME=/home/sacredmusic && export TEXMFCNF=.: && lamed -output-directory=tmp -interaction=nonstopmode $nametexS 2>&1", $lamedOutput, $lamedRetVal);
// Run dvipdfm on the .dvi
//  exec("export TEXMFCONFIG=/home/sacredmusic/texmf && export TEXMFHOME=/home/sacredmusic/texmf && export HOME=/home/sacredmusic && dvipdfm -o $namepdfS $namedviS 2>&1", $dvipdfmOutput, $dvipdfmRetVal);
  //if($lamedRetVal){
  if($lualatexRetVal){
    header("Content-type: text/plain");
    echo implode("\n",$lualatexOutput);
    return;
  }
  $deletepdf = ($dirEdition=='' or $outFileName=='Untitled');
  $finalpdf = ($deletepdf?'tmp/tmp.':"$odir/")."$outFileName.pdf";
  $finalpdfS = escapeshellarg($finalpdf);
  

// Copy the pdf into another directory, or upload to an FTP site.
  if($croppdf) {
    exec("pdfcrop $namepdf $finalpdf 2>&1", $croppdfOutput, $croppdfRetVal);
    if($croppdfRetVal){
      header("Content-type: text/plain");
      echo implode("\n",$croppdfOutput);
      return;
    }
  }
  rename($namepdf,$finalpdf);
  if($publish) {
    if($deletepdf) {
      header("Content-type: text/plain");
      echo "You can only publish a score if it has a title/filename";
      return;
    }
    if(!file_exists("/home/sacredmusic/downloads/$dirEdition")) {
      mkdir("/home/sacredmusic/downloads/$dirEdition", 0775, true);
    }
    copy($finalpdf,"/home/sacredmusic/downloads/$dirEdition/$outFileName.pdf");
    //header('HTTP/1.1 301 Moved Permanently');
    //header("Location: /downloads/$dirEdition/$outFileName.pdf");
    header("Content-type: text/plain");
    echo "Location: /downloads/$dirEdition/$outFileName.pdf";
    return;
  }
  //Instead of just renaming it, let's subset the fonts:
  //exec("gs -q -dNOPAUSE -dBATCH -dSAFER -sDEVICE=pdfwrite -dCompatibilityLevel=1.3 -dEmbedAllFonts=true -dSubsetFonts=true -sOutputFile=$finalpdfS $namepdf");
  //Warning
  header("Content-type: $fmtmime");
  if(!$save) {
    if($format=='pdf'){
      if($subsetfonts) {
        passthru("gs -q -dNOPAUSE -dBATCH -dSAFER -sDEVICE=pdfwrite -dCompatibilityLevel=1.3 -dEmbedAllFonts=true -dSubsetFonts=true -sOutputFile=- $finalpdfS");
      } else {
        $handle = fopen($finalpdf, 'r');
        fpassthru($handle);
        fclose($handle);
      }
    } else {
      passthru("convert -density 480 $finalpdfS +append -resize 25% -limit memory 128MB -limit map 256MB $format:-");
    }
  }
//  @unlink($namepdf);
//  @unlink($namedvi);
  //@unlink($nametex);
//  @unlink($nameaux);
//  @unlink($namelog);
  if($ofilename != 'gabc') {
//    @unlink($namegtex);
  }
  @unlink($namegabc);
}
?>